'''
重命名项目名称
Created on 2015年7月31日
@author: anyang
'''
from builtins import UnicodeDecodeError
import fnmatch
import logging
import os

# 配置日志信息
logging.basicConfig(level=logging.DEBUG,
                    format='%(message)s',
                    datefmt='%Y-%m-%d %H:%M',
                    filename='项目文件替换信息.log',
                    filemode='w')

def all_files(root, patterns="*" , single_level=False, yield_folders=False):
        patterns = patterns.split(";")
        L = []
        for path, subdirs, files in os.walk(root): 
            if yield_folders:
                files.extend(subdirs)
            files.sort()
            for name in files:
                for pattern in patterns:
                    if fnmatch.fnmatch(name, pattern):
                        L.append(os.path.join(path, name))
                        break
            if single_level:
                break
        return L


# 是否为Debug模式，只输出更改内容，不实际进行改动
isDebug = True

# 设置要修改的项目文件夹 
projectFolder = "G:\\dttmsst_测试"

# 旧的项目名称
oldProjectName = "yczxsst"

# 新的项目名称
newProjectName = "anyangsst"
    
# 修改项目文件名
path2s = all_files(projectFolder, oldProjectName + "*", False, True)
path2s.sort(reverse=True)
for path2 in path2s:
    logging.info("重命名:%s  ==> %s " % (path2 , os.path.split(path2)[0] + "\\" + newProjectName + os.path.splitext(path2)[1])) 
    if not isDebug:
        os.rename(path2, os.path.split(path2)[0] + "\\" + newProjectName + os.path.splitext(path2)[1])

# 替换文件中所有关键字
for path3 in all_files(projectFolder, "*.*", False, True):
    if os.path.splitext(path3)[1] in [".dll", ".jpg", ".png", ".lib", ".so", ".mng", ".psd", ".db", ".obj"]:
        # logging.info("没有替换：",path3)
        continue
    logging.info("替换了:%s" % path3)
    if not isDebug:
        try:
            with open(path3, "r+" , encoding='gbk') as f :
                content = f.read()
                f.seek(0)
                f.truncate()
                f.write(content.replace(oldProjectName, newProjectName))
        except UnicodeDecodeError as e:
                logging.info("替换出错啦:%s" % path3)
                print("替换出错:%s" % path3)

